package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.lang.model.element.Name;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    //增加菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.saveWith(dishDto);
        return R.success("新增成功");
    }


    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构建分页构造器
        Page<Dish> pageinfo = new Page<>(page,pageSize);

        //构建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询
       /* if (name!=null&&name!=""){
        lqw.like(Dish::getName,name);}*/
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        dishService.page(pageinfo,lqw);
        //要包含分类名称的结果
        Page<DishDto> resultPage = new Page<>();
        //将pageinfo中的数据复制到resultPage中
        BeanUtils.copyProperties(pageinfo,resultPage,"records");
        //从数据库中查询到集合,不包含分类名
        List<Dish> records = pageinfo.getRecords();
        ArrayList<DishDto> resultList = new ArrayList<>();

        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            //设置分类名称
            Category category = categoryService.getById(record.getCategoryId());
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            resultList.add(dishDto);
        }
        resultPage.setRecords(resultList);


        return R.success(resultPage);

    }

    //根据id查询  用于修改菜品页面的数据回显
    @GetMapping("/{id}")
    @Cacheable(value = "dish",key = "#id", unless = "#result == null")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    //修改
    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        dishService.updateWithFlavor(dishDto);
            return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtolist =null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtolist = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtolist!=null){
            return R.success(dishDtolist);
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish.getName());
        //根据id精确查询
        lqw.eq(Dish::getCategoryId,dish.getCategoryId());
        //排序
        lqw.orderByAsc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        dishDtolist = new ArrayList<>();
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());

            LambdaQueryWrapper<DishFlavor> Dflqw = new LambdaQueryWrapper<>();
            Dflqw.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> list1 = dishFlavorService.list(Dflqw);
            dishDto.setFlavors(list1);
            dishDtolist.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtolist,24, TimeUnit.HOURS);

        return R.success(dishDtolist);
    }

    //停售与启售
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
       /* Dish dish = new Dish();
        dish.setStatus(status);
        dishService.update(dish,lqw);*/
       /* LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
        luw.in(Dish::getId,ids);
        luw.set(Dish::getStatus,status);
        dishService.update(luw);*/

        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("");
    }
    //删除菜品
    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.deleteWith(ids);
        return R.success("删除成功");

    }


}    